<template>
	<view class="container">
		<view class="header">
			<view class="title">停车服务申请</view>
			<view class="subtitle">申请长期停车位</view>
		</view>
		
		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 选择车辆 -->
			<view class="form-item">
				<view class="form-label">选择车辆</view>
				<view class="vehicle-selector" @click="showVehicleSelector">
					<view v-if="selectedVehicle" class="selected-vehicle">
						<text class="vehicle-plate">{{ selectedVehicle.plate_number }}</text>
						<text class="vehicle-info">{{ selectedVehicle.vehicle_type }} {{ selectedVehicle.brand || '' }} {{ selectedVehicle.model || '' }}</text>
					</view>
					<view v-else class="placeholder">请选择车辆</view>
					<text class="arrow">></text>
				</view>
			</view>
			
			<!-- 选择车位 -->
			<view class="form-item">
				<view class="form-label">选择车位</view>
				<view class="parking-space-selector" @click="showParkingSpaceSelector">
					<view v-if="selectedParkingSpace" class="selected-parking-space">
						<text class="parking-space-number">{{ selectedParkingSpace.unit_number }}</text>
						<text class="parking-space-info">{{ selectedParkingSpace.location }}</text>
					</view>
					<view v-else class="placeholder">请选择车位</view>
					<text class="arrow">></text>
				</view>
			</view>
			
			<!-- 期望开始日期 -->
			<view class="form-item">
				<view class="form-label">期望开始日期</view>
				<view class="date-picker" @click="showDatePicker('start')">
					<text v-if="formData.expectedStartDate">{{ formData.expectedStartDate }}</text>
					<text v-else class="placeholder">请选择日期</text>
					<text class="arrow">></text>
				</view>
			</view>
			
			<!-- 期望租赁时长 -->
			<view class="form-item">
				<view class="form-label">租赁时长(月)</view>
				<view class="duration-selector">
					<view 
						v-for="(duration, index) in durationOptions" 
						:key="index"
						:class="['duration-option', formData.expectedDuration === duration ? 'selected' : '']"
						@click="formData.expectedDuration = duration"
					>
						{{ duration }}
					</view>
				</view>
			</view>
			
			<!-- 申请说明 -->
			<view class="form-item">
				<view class="form-label">申请说明 (选填)</view>
				<textarea 
					class="form-textarea" 
					placeholder="请输入申请说明或特殊需求" 
					v-model="formData.remarks"
					maxlength="200"
				></textarea>
				<text class="char-counter">{{ formData.remarks.length }}/200</text>
			</view>
		</view>
		
		<!-- 申请流程说明 -->
		<view class="process-guide">
			<view class="guide-title">申请流程</view>
			<view class="guide-steps">
				<view class="step">
					<view class="step-icon">1</view>
					<view class="step-text">提交申请</view>
				</view>
				<view class="step-line"></view>
				<view class="step">
					<view class="step-icon">2</view>
					<view class="step-text">管理员初审</view>
				</view>
				<view class="step-line"></view>
				<view class="step">
					<view class="step-icon">3</view>
					<view class="step-text">填写合同</view>
				</view>
				<view class="step-line"></view>
				<view class="step">
					<view class="step-icon">4</view>
					<view class="step-text">最终审批</view>
				</view>
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view class="bottom-action">
			<button class="submit-btn" @click="submitApplication">提交申请</button>
		</view>
		
		<!-- 车辆选择弹窗 -->
		<view class="custom-popup" v-if="showVehiclePopupFlag">
			<view class="popup-mask" @click="closeVehicleSelector"></view>
			<view class="popup-content popup-bottom">
				<view class="popup-header">
					<text class="popup-title">选择车辆</text>
					<text class="popup-close" @click="closeVehicleSelector">×</text>
				</view>
				<view class="vehicle-list">
					<view 
						class="vehicle-item" 
						v-for="(vehicle, index) in vehicles" 
						:key="vehicle.vehicle_id"
						@click="selectVehicle(vehicle)"
					>
						<view class="vehicle-info">
							<text class="vehicle-plate">{{ vehicle.plate_number }}</text>
							<text class="vehicle-detail">{{ vehicle.vehicle_type }} {{ vehicle.brand || '' }} {{ vehicle.model || '' }}</text>
						</view>
						<text class="vehicle-select-icon" v-if="selectedVehicle && selectedVehicle.vehicle_id === vehicle.vehicle_id">✓</text>
					</view>
				</view>
				<view class="add-vehicle" @click="navigateToAddVehicle">
					<text class="add-icon">+</text>
					<text>添加新车辆</text>
				</view>
			</view>
		</view>
		
		<!-- 车位选择弹窗 -->
		<view class="custom-popup" v-if="showParkingSpacePopupFlag">
			<view class="popup-mask" @click="closeParkingSpaceSelector"></view>
			<view class="popup-content popup-bottom">
				<view class="popup-header">
					<text class="popup-title">选择车位</text>
					<text class="popup-close" @click="closeParkingSpaceSelector">×</text>
				</view>
				<view v-if="isLoadingParkingSpaces" class="loading-container">
					<text>加载中...</text>
				</view>
				<view v-else-if="parkingSpaces.length === 0" class="empty-container">
					<text>暂无可用车位</text>
				</view>
				<view v-else class="parking-space-list">
					<view 
						class="parking-space-item" 
						v-for="(space, index) in parkingSpaces" 
						:key="space.unit_id"
						@click="selectParkingSpace(space)"
					>
						<view class="parking-space-info">
							<text class="parking-space-number">{{ space.unit_number }}</text>
							<text class="parking-space-detail">{{ space.location }}</text>
							<text class="parking-space-price" v-if="space.rental_price">¥{{ space.rental_price }}/月</text>
						</view>
						<text class="parking-space-select-icon" v-if="selectedParkingSpace && selectedParkingSpace.unit_id === space.unit_id">✓</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 日期选择弹窗 -->
		<view class="custom-popup" v-if="showDatePickerFlag">
			<view class="popup-mask" @click="closeDatePicker"></view>
			<view class="popup-content popup-bottom">
				<view class="popup-header">
					<text class="popup-title">选择日期</text>
					<text class="popup-close" @click="closeDatePicker">×</text>
				</view>
				<view class="date-picker-content">
					<picker mode="date" :value="formData.expectedStartDate" @change="onDateChange" :start="startDate">
						<view class="uni-input">{{ formData.expectedStartDate || '请选择日期' }}</view>
					</picker>
					<button class="confirm-btn" @click="confirmDatePicker">确认</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { getVehicleList } from '@/api/vehicle.js'
	import { createParkingApplication, getAvailableParkingSpaces } from '@/api/parking.js'
	
	export default {
		components: {
			// uniPopup, // Removed as per edit hint
			// uniCalendar // Removed as per edit hint
		},
		data() {
			return {
				vehicles: [],
				selectedVehicle: null,
				parkingSpaces: [],
				selectedParkingSpace: null,
				isLoadingParkingSpaces: false,
				datePickerType: '',
				startDate: this.getFormattedDate(new Date()),
				durationOptions: [1, 3, 6, 12],
				formData: {
					expectedStartDate: '',
					expectedDuration: 3,
					remarks: '',
				},
				isLoading: false,
				showVehiclePopupFlag: false, // Added for custom popup
				showParkingSpacePopupFlag: false, // Added for custom popup
				showDatePickerFlag: false // Added for custom popup
			}
		},
		onLoad() {
			// 初始化日期为明天
			const tomorrow = new Date();
			tomorrow.setDate(tomorrow.getDate() + 1);
			this.formData.expectedStartDate = this.getFormattedDate(tomorrow);
			
			// 页面加载时获取车位列表
			setTimeout(() => {
				this.fetchParkingSpaces();
			}, 500);
		},
		onShow() {
			// 每次页面显示时获取最新车辆数据
			this.fetchVehicles();
		},
		methods: {
			// 获取车辆列表
			fetchVehicles() {
				// 检查登录状态
				const token = uni.getStorageSync('token');
				if (!token) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login'
						});
					}, 1500);
					return;
				}
				
				this.isLoading = true;
				
				// 调用API获取当前用户的车辆列表
				getVehicleList()
					.then(data => {
						this.vehicles = data.results || [];
						if (this.vehicles.length > 0 && !this.selectedVehicle) {
							this.selectedVehicle = this.vehicles[0];
						}
					})
					.catch(err => {
						console.error('获取车辆列表失败', err);
						uni.showToast({
							title: err.message || '获取车辆列表失败',
							icon: 'none'
						});
					})
					.finally(() => {
						this.isLoading = false;
					});
			},
			
			// 获取可用车位列表
			fetchParkingSpaces() {
				this.isLoadingParkingSpaces = true;
				
				console.log('开始获取车位列表...');
				
				// 调用API获取可用车位
				getAvailableParkingSpaces()
					.then(res => {
						console.log('获取车位列表成功:', res);
						if (res && res.data) {
							this.parkingSpaces = res.data;
							console.log('车位数量:', this.parkingSpaces.length);
						} else {
							console.log('车位数据为空');
							this.parkingSpaces = [];
						}
					})
					.catch(err => {
						console.error('获取车位列表失败', err);
						uni.showToast({
							title: err.message || '获取车位列表失败',
							icon: 'none'
						});
						this.parkingSpaces = [];
					})
					.finally(() => {
						this.isLoadingParkingSpaces = false;
					});
			},
			
			// 显示车辆选择器
			showVehicleSelector() {
				this.showVehiclePopupFlag = true; // Open custom popup
				// this.$refs.vehiclePopup.open(); // Original uni-popup open
			},
			
			// 关闭车辆选择器
			closeVehicleSelector() {
				this.showVehiclePopupFlag = false; // Close custom popup
				// this.$refs.vehiclePopup.close(); // Original uni-popup close
			},
			
			// 选择车辆
			selectVehicle(vehicle) {
				this.selectedVehicle = vehicle;
				this.closeVehicleSelector();
			},
			
			// 显示车位选择器
			showParkingSpaceSelector() {
				// 打开弹窗前先获取车位列表
				this.fetchParkingSpaces();
				this.showParkingSpacePopupFlag = true; // Open custom popup
				// this.$refs.parkingSpacePopup.open(); // Original uni-popup open
			},
			
			// 关闭车位选择器
			closeParkingSpaceSelector() {
				this.showParkingSpacePopupFlag = false; // Close custom popup
				// this.$refs.parkingSpacePopup.close(); // Original uni-popup close
			},
			
			// 选择车位
			selectParkingSpace(space) {
				this.selectedParkingSpace = space;
				this.closeParkingSpaceSelector();
			},
			
			// 跳转到添加车辆页面
			navigateToAddVehicle() {
				this.closeVehicleSelector();
				uni.navigateTo({
					url: '/pages/parking/add'
				});
			},
			
			// 显示日期选择器
			showDatePicker(type) {
				this.datePickerType = type;
				this.showDatePickerFlag = true; // Open custom popup
				// this.$refs.calendar.open(); // Original uni-calendar open
			},
			
			// 关闭日期选择器
			closeDatePicker() {
				this.showDatePickerFlag = false; // Close custom popup
			},
			
			// 日期选择器确认
			onDateChange(e) {
				this.formData.expectedStartDate = e.detail.value;
			},
			
			// 日期选择器确认
			confirmDatePicker() {
				this.closeDatePicker();
			},
			
			// 格式化日期为YYYY-MM-DD
			getFormattedDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			
			// 提交申请
			submitApplication() {
				// 表单验证
				if (!this.selectedVehicle) {
					uni.showToast({
						title: '请选择车辆',
						icon: 'none'
					});
					return;
				}
				
				if (!this.selectedParkingSpace) {
					uni.showToast({
						title: '请选择车位',
						icon: 'none'
					});
					return;
				}
				
				if (!this.formData.expectedStartDate) {
					uni.showToast({
						title: '请选择期望开始日期',
						icon: 'none'
					});
					return;
				}
				
				// 显示加载提示
				uni.showLoading({
					title: '提交中...'
				});
				
				// 准备提交数据
				const applicationData = {
					vehicle_id: this.selectedVehicle.vehicle_id,
					unit_id: this.selectedParkingSpace.unit_id,
					expected_start_date: this.formData.expectedStartDate,
					expected_duration: this.formData.expectedDuration,
					remarks: this.formData.remarks
				};
				
				// 调用API提交申请
				createParkingApplication(applicationData)
					.then(res => {
						uni.hideLoading();
						uni.showToast({
							title: '申请提交成功',
							icon: 'success'
						});
						
						// 延迟跳转到申请列表页
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/parking/application-list'
							});
						}, 1500);
					})
					.catch(err => {
						uni.hideLoading();
						console.error('提交申请失败', err);
						uni.showToast({
							title: err.message || '提交申请失败',
							icon: 'none'
						});
					});
			}
		}
	}
</script>

<style>
	.container {
		padding: 30rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	.header {
		margin-bottom: 30rpx;
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.subtitle {
		font-size: 26rpx;
		color: #666;
	}
	
	.form-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;
	}
	
	.form-item {
		margin-bottom: 30rpx;
	}
	
	.form-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 15rpx;
		font-weight: 500;
	}
	
	.vehicle-selector, .date-picker, .parking-space-selector {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #f8f8f8;
		padding: 20rpx;
		border-radius: 8rpx;
	}
	
	.selected-vehicle, .selected-parking-space {
		display: flex;
		flex-direction: column;
	}
	
	.vehicle-plate, .parking-space-number {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.vehicle-info, .parking-space-info {
		font-size: 24rpx;
		color: #666;
		margin-top: 5rpx;
	}
	
	.placeholder {
		color: #999;
	}
	
	.arrow {
		color: #999;
		font-size: 32rpx;
	}
	
	.duration-selector {
		display: flex;
		justify-content: space-between;
	}
	
	.duration-option {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		margin: 0 10rpx;
		background-color: #f8f8f8;
		border-radius: 8rpx;
		font-size: 28rpx;
		color: #333;
	}
	
	.duration-option.selected {
		background-color: #007aff;
		color: #fff;
	}
	
	.duration-option:first-child {
		margin-left: 0;
	}
	
	.duration-option:last-child {
		margin-right: 0;
	}
	
	.form-textarea {
		width: 100%;
		height: 200rpx;
		background-color: #f8f8f8;
		padding: 20rpx;
		border-radius: 8rpx;
		font-size: 28rpx;
		box-sizing: border-box;
	}
	
	.char-counter {
		font-size: 24rpx;
		color: #999;
		text-align: right;
		margin-top: 10rpx;
	}
	
	.process-guide {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 100rpx;
	}
	
	.guide-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
	}
	
	.guide-steps {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	
	.step {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 120rpx;
	}
	
	.step-icon {
		width: 60rpx;
		height: 60rpx;
		background-color: #007aff;
		color: #fff;
		border-radius: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
		margin-bottom: 10rpx;
	}
	
	.step-text {
		font-size: 24rpx;
		color: #666;
		text-align: center;
	}
	
	.step-line {
		flex: 1;
		height: 2rpx;
		background-color: #ddd;
		margin: 0 5rpx;
		margin-bottom: 30rpx;
	}
	
	.bottom-action {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 20rpx 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.submit-btn {
		background-color: #007aff;
		color: #fff;
		font-size: 32rpx;
		padding: 20rpx 0;
		border-radius: 45rpx;
		text-align: center;
	}
	
	/* 弹窗样式 */
	.custom-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1000;
	}
	
	.popup-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
	}
	
	.popup-content {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		padding: 30rpx;
		max-height: 70vh;
		display: flex;
		flex-direction: column;
	}
	
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}
	
	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.popup-close {
		font-size: 40rpx;
		color: #999;
	}
	
	.vehicle-list, .parking-space-list {
		max-height: 50vh;
		overflow-y: auto;
	}
	
	.vehicle-item, .parking-space-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;
	}
	
	.vehicle-detail, .parking-space-detail {
		font-size: 24rpx;
		color: #666;
		margin-top: 5rpx;
	}
	
	.parking-space-price {
		font-size: 24rpx;
		color: #ff6b00;
		margin-top: 5rpx;
	}
	
	.vehicle-select-icon, .parking-space-select-icon {
		color: #007aff;
		font-size: 40rpx;
	}
	
	.add-vehicle {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 30rpx 0;
		color: #007aff;
		font-size: 28rpx;
	}
	
	.add-icon {
		margin-right: 10rpx;
		font-size: 32rpx;
	}
	
	.loading-container, .empty-container {
		padding: 50rpx 0;
		text-align: center;
		color: #999;
	}
	
	.date-picker-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx 0;
	}
	
	.uni-input {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 32rpx;
		color: #333;
		border: 1rpx solid #eee;
		border-radius: 8rpx;
		margin-bottom: 30rpx;
		background-color: #f8f8f8;
	}
	
	.confirm-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 32rpx;
		color: #fff;
		background-color: #007aff;
		border-radius: 45rpx;
		text-align: center;
	}
</style> 